import {
  serialize
} from '../util/util'
import {
  getStore
} from '../util/store'
import axios from 'axios'
import router from '@/router/router'
import NProgress from 'nprogress' // progress bar
import errorCode from '../const/errorCode'
import {
  Message,
  MessageBox
} from 'element-ui'
import 'nprogress/nprogress.css'
import store from '../store' // progress bar style
axios.defaults.timeout = 30000
// 返回其他状态吗
var errorCount = 1
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  const ORG_ID = getStore({
    name: 'orgId'
  })
  const isToken = (config.headers || {}).isToken === false
  const token = store.getters.access_token || ''
  if (token && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + token // token
  }
  // if (ORG_ID && config.headers['LOGIN-USER-TYPE'] !== 'superuser') {
  //   config.headers['ORG-ID'] = ORG_ID // 租户ID
  // }
  if (config.params && config.params.hasOwnProperty('username') && config.params.hasOwnProperty('password')) {
    if (ORG_ID) {
      if (config.headers['ORG-ID'] === 0) config.params.username = `${config.params.username}$0`
      else config.params.username = `${config.params.username}$${ORG_ID}`
    } else {
      config.params.username = `${config.params.username}$0`
    }
  }

  // headers中配置serialize为true开启序列化
  if (config.method === 'post' && config.headers.serialize) {
    config.data = serialize(config.data)
    delete config.data.serialize
  }
  return config
}, error => {
  return Promise.reject(error)
})

// HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done()
  const status = Number(res.status) || 200
  const message = (res.data.meta ? res.data.meta.message : res.data.msg) || errorCode[status] || errorCode['default']

  if (status !== 200 || (res.data.meta ? !res.data.meta.success : false)) {
    if (status === 401) {
      if(errorCount===1){ //errorCount401提示框
        MessageBox.confirm('凭证失效，是否跳转登录界面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          errorCount=1
          store.dispatch('FedLogOut').then(() => {
            router.push({
              path: '/login',
            })
          })
        }).catch(() => {
          errorCount=1
        });
        errorCount++
      }
      console.log('errorCount',errorCount)
    }else {
      Message({
        dangerouslyUseHTMLString: true,
        message: message,
        type: 'error'
      })
    }
    /* 许可证过期唯一标识：license_invalid（License expired ），跳转激活页面
       许可证锁定唯一标识：license_locked（License locked），跳转登录页面  */
    // 判断许可证是否激活/过期/锁定
    if (res.data.meta.message === 'License expired') {
      router.push({
        path: '/licenseActive',
      })
    } else if (res.data.meta.message === 'License locked') {
      store.dispatch('FedLogOut').then(() => {
        router.push({
          path: '/login',
        })
      })
    }
    return Promise.reject(new Error(message))
  }

  return res
}, error => {
  NProgress.done()
  return Promise.reject(new Error(error))
})

export default axios
